/**
 * 退款记录管理服务
 * 利用现有数据库结构管理退款状态和记录追踪
 */

const { query } = require('../config/db');

class RefundRecordService {
  
  /**
   * 创建退款记录
   * @param {Object} refundData - 退款数据
   * @returns {Promise<Object>} 创建结果
   */
  async createRefundRecord(refundData) {
    try {
      const {
        orderId,
        refundNumber,
        refundAmount,
        refundType,
        refundReason,
        wechatRefundId,
        serviceFee = 0,
        calculation = null
      } = refundData;

      // 获取当前订单信息
      const orderQuery = `
        SELECT id, order_number, payment_method, status
        FROM orders
        WHERE id = ?
      `;
      
      const orders = await query(orderQuery, [orderId]);
      if (orders.length === 0) {
        throw new Error('订单不存在');
      }

      const order = orders[0];
      
      // 构建退款记录
      const refundRecord = {
        refund_number: refundNumber,
        refund_amount: refundAmount,
        service_fee: serviceFee,
        refund_reason: refundReason,
        refund_type: refundType,
        wechat_refund_id: wechatRefundId,
        refund_status: 'processing',
        refund_time: new Date().toISOString(),
        calculation: calculation
      };

      // 解析现有的支付方法信息
      let paymentInfo = {};
      try {
        if (order.payment_method && order.payment_method.startsWith('{')) {
          paymentInfo = JSON.parse(order.payment_method);
        } else {
          paymentInfo = {
            original_method: order.payment_method || 'wechat_pay'
          };
        }
      } catch (error) {
        paymentInfo = {
          original_method: order.payment_method || 'wechat_pay'
        };
      }

      // 添加退款信息
      if (!paymentInfo.refund_records) {
        paymentInfo.refund_records = [];
      }
      paymentInfo.refund_records.push(refundRecord);

      // 更新订单的payment_method字段
      const updateQuery = `
        UPDATE orders
        SET payment_method = ?,
            updated_at = NOW()
        WHERE id = ?
      `;

      await query(updateQuery, [JSON.stringify(paymentInfo), orderId]);

      console.log(`📝 退款记录已创建 - 订单: ${order.order_number}, 退款单号: ${refundNumber}`);

      return {
        success: true,
        refundRecord: refundRecord
      };

    } catch (error) {
      console.error('创建退款记录失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 更新退款状态
   * @param {number} orderId - 订单ID
   * @param {string} refundNumber - 退款单号
   * @param {string} status - 新状态
   * @param {Object} additionalData - 额外数据
   * @returns {Promise<Object>} 更新结果
   */
  async updateRefundStatus(orderId, refundNumber, status, additionalData = {}) {
    try {
      // 获取当前订单信息
      const orderQuery = `
        SELECT id, order_number, payment_method
        FROM orders
        WHERE id = ?
      `;
      
      const orders = await query(orderQuery, [orderId]);
      if (orders.length === 0) {
        throw new Error('订单不存在');
      }

      const order = orders[0];
      
      // 解析支付信息
      let paymentInfo = {};
      try {
        paymentInfo = JSON.parse(order.payment_method);
      } catch (error) {
        throw new Error('无法解析退款记录');
      }

      if (!paymentInfo.refund_records || !Array.isArray(paymentInfo.refund_records)) {
        throw new Error('未找到退款记录');
      }

      // 查找并更新对应的退款记录
      let recordFound = false;
      paymentInfo.refund_records = paymentInfo.refund_records.map(record => {
        if (record.refund_number === refundNumber) {
          recordFound = true;
          return {
            ...record,
            refund_status: status,
            updated_time: new Date().toISOString(),
            ...additionalData
          };
        }
        return record;
      });

      if (!recordFound) {
        throw new Error('未找到对应的退款记录');
      }

      // 更新数据库
      const updateQuery = `
        UPDATE orders
        SET payment_method = ?,
            updated_at = NOW()
        WHERE id = ?
      `;

      await query(updateQuery, [JSON.stringify(paymentInfo), orderId]);

      console.log(`🔄 退款状态已更新 - 订单: ${order.order_number}, 退款单号: ${refundNumber}, 状态: ${status}`);

      return {
        success: true,
        message: '退款状态更新成功'
      };

    } catch (error) {
      console.error('更新退款状态失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 获取订单的退款记录
   * @param {number} orderId - 订单ID
   * @returns {Promise<Object>} 退款记录
   */
  async getRefundRecords(orderId) {
    try {
      const orderQuery = `
        SELECT 
          id, order_number, payment_method, status,
          total_amount, discount_amount, final_amount
        FROM orders
        WHERE id = ?
      `;
      
      const orders = await query(orderQuery, [orderId]);
      if (orders.length === 0) {
        return {
          success: false,
          error: '订单不存在'
        };
      }

      const order = orders[0];
      let refundRecords = [];

      // 解析退款记录
      try {
        if (order.payment_method && order.payment_method.startsWith('{')) {
          const paymentInfo = JSON.parse(order.payment_method);
          refundRecords = paymentInfo.refund_records || [];
        }
      } catch (error) {
        // 解析失败，返回空记录
      }

      return {
        success: true,
        data: {
          order_id: orderId,
          order_number: order.order_number,
          order_status: order.status,
          order_amounts: {
            total_amount: parseFloat(order.total_amount),
            discount_amount: parseFloat(order.discount_amount),
            final_amount: parseFloat(order.final_amount)
          },
          refund_records: refundRecords
        }
      };

    } catch (error) {
      console.error('获取退款记录失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 获取用户的所有退款记录
   * @param {number} userId - 用户ID
   * @param {Object} options - 查询选项
   * @returns {Promise<Object>} 退款记录列表
   */
  async getUserRefundRecords(userId, options = {}) {
    try {
      const { page = 1, limit = 10, status = null } = options;
      const offset = (page - 1) * limit;

      let whereClause = 'WHERE o.user_id = ?';
      let queryParams = [userId];

      // 只查询有退款记录的订单
      whereClause += ' AND o.payment_method LIKE ?';
      queryParams.push('%refund_records%');

      if (status) {
        whereClause += ' AND o.status = ?';
        queryParams.push(status);
      }

      const ordersQuery = `
        SELECT 
          o.id, o.order_number, o.status, o.payment_method,
          o.total_amount, o.discount_amount, o.final_amount,
          o.planned_start_time, o.planned_end_time,
          o.created_at, o.updated_at,
          pl.name as parking_lot_name,
          pl.address as parking_lot_address
        FROM orders o
        LEFT JOIN parking_lots pl ON o.parking_lot_id = pl.id
        ${whereClause}
        ORDER BY o.updated_at DESC
        LIMIT ? OFFSET ?
      `;

      queryParams.push(limit, offset);

      const orders = await query(ordersQuery, queryParams);
      
      // 解析每个订单的退款记录
      const refundRecords = [];
      for (const order of orders) {
        try {
          if (order.payment_method && order.payment_method.startsWith('{')) {
            const paymentInfo = JSON.parse(order.payment_method);
            if (paymentInfo.refund_records && Array.isArray(paymentInfo.refund_records)) {
              paymentInfo.refund_records.forEach(record => {
                refundRecords.push({
                  ...record,
                  order_id: order.id,
                  order_number: order.order_number,
                  order_status: order.status,
                  parking_lot_name: order.parking_lot_name,
                  parking_lot_address: order.parking_lot_address,
                  order_created_at: order.created_at
                });
              });
            }
          }
        } catch (error) {
          console.warn(`解析订单 ${order.order_number} 的退款记录失败:`, error);
        }
      }

      // 按退款时间排序
      refundRecords.sort((a, b) => new Date(b.refund_time) - new Date(a.refund_time));

      return {
        success: true,
        data: {
          records: refundRecords,
          pagination: {
            page,
            limit,
            total: refundRecords.length
          }
        }
      };

    } catch (error) {
      console.error('获取用户退款记录失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * 统计退款数据
   * @param {Object} options - 统计选项
   * @returns {Promise<Object>} 统计结果
   */
  async getRefundStatistics(options = {}) {
    try {
      const { startDate, endDate, parkingLotId } = options;
      
      let whereClause = 'WHERE o.payment_method LIKE ?';
      let queryParams = ['%refund_records%'];

      if (startDate) {
        whereClause += ' AND o.created_at >= ?';
        queryParams.push(startDate);
      }

      if (endDate) {
        whereClause += ' AND o.created_at <= ?';
        queryParams.push(endDate);
      }

      if (parkingLotId) {
        whereClause += ' AND o.parking_lot_id = ?';
        queryParams.push(parkingLotId);
      }

      const ordersQuery = `
        SELECT 
          o.id, o.order_number, o.payment_method,
          o.total_amount, o.final_amount
        FROM orders o
        ${whereClause}
      `;

      const orders = await query(ordersQuery, queryParams);
      
      let totalRefundAmount = 0;
      let totalRefundCount = 0;
      const refundTypes = {};

      // 统计退款数据
      for (const order of orders) {
        try {
          if (order.payment_method && order.payment_method.startsWith('{')) {
            const paymentInfo = JSON.parse(order.payment_method);
            if (paymentInfo.refund_records && Array.isArray(paymentInfo.refund_records)) {
              paymentInfo.refund_records.forEach(record => {
                totalRefundAmount += parseFloat(record.refund_amount || 0);
                totalRefundCount++;
                
                const type = record.refund_type || 'unknown';
                if (!refundTypes[type]) {
                  refundTypes[type] = { count: 0, amount: 0 };
                }
                refundTypes[type].count++;
                refundTypes[type].amount += parseFloat(record.refund_amount || 0);
              });
            }
          }
        } catch (error) {
          console.warn(`统计订单 ${order.order_number} 的退款数据失败:`, error);
        }
      }

      return {
        success: true,
        data: {
          total_refund_amount: Math.round(totalRefundAmount * 100) / 100,
          total_refund_count: totalRefundCount,
          refund_types: refundTypes,
          average_refund_amount: totalRefundCount > 0 ? 
            Math.round((totalRefundAmount / totalRefundCount) * 100) / 100 : 0
        }
      };

    } catch (error) {
      console.error('获取退款统计失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }
}

module.exports = new RefundRecordService();
